const Role = require("../models/roleModel");

const createRole = async (req, res) => {
  try {
    const { roleName,  description, permissions } = req.body;

    if (!roleName) {
      return res.status(400).json({ message: "Role Name are required." });
    }

    const newRole = new Role({
      roleName,
      
      description,
      permissions, 
    });

    await newRole.save();
    res.status(201).json({ message: "Role created successfully", role: newRole });
  } catch (error) {
    console.error("Error creating role:", error);
    res.status(500).json({ message: "Server error" });
  }
};

const getRoles = async (req, res) => {
  try {
    const roles = await Role.find();
    res.json({ roles });
  } catch (error) {
    console.error("Error fetching roles:", error);
    res.status(500).json({ message: "Server error" });
  }
};



  const updateRole = async (req, res) => {
    try {
      
      const id = req.params.id.trim();
      const { roleName,  description, permissions } = req.body;
      
      const updatedRole = await Role.findByIdAndUpdate(
        id,
        { roleName,  description, permissions },
        { new: true }
      );
      
      if (!updatedRole) {
        return res.status(404).json({ message: "Role not found" });
      }
      
      res.status(200).json({ message: "Role updated successfully", role: updatedRole });
    } catch (error) {
      console.error("Error updating role:", error);
      res.status(500).json({ message: "Server error", error: error.message });
    }
  };
  



// Delete Role
const deleteRole = async (req, res) => {
  try {
    
    const id = req.params.id.trim();
    const deletedRole = await Role.findByIdAndDelete(id);
    if (!deletedRole) {
      return res.status(404).json({ success: false, message: "Role not found" });
    }
    return res.status(200).json({ success: true, message: "Role deleted successfully" });
  } catch (error) {
    console.error("Error deleting role:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

module.exports = { createRole, getRoles, updateRole, deleteRole};
